/**
 * 应用全局状态
 */
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { THEMES, STORAGE_KEYS } from '@/config'
import { getStorage, setStorage } from '@/utils'
import type { Theme } from '@/types'

export const useAppStore = defineStore('app', () => {
  // 状态
  const theme = ref<Theme>(getStorage(STORAGE_KEYS.THEME, true, THEMES.LIGHT) as Theme)
  const appReady = ref(false)

  // 方法
  /**
   * 初始化应用
   */
  const initApp = async () => {
    // 这里可以加载应用初始化数据
    // 例如：检查登录状态、加载配置等

    // 模拟初始化过程
    return new Promise<void>(resolve => {
      setTimeout(() => {
        appReady.value = true
        resolve()
      }, 500)
    })
  }

  /**
   * 设置主题
   */
  const setTheme = (newTheme: Theme) => {
    theme.value = newTheme
    setStorage(STORAGE_KEYS.THEME, newTheme)
  }

  /**
   * 切换主题
   */
  const toggleTheme = () => {
    const newTheme = theme.value === THEMES.LIGHT ? THEMES.DARK : THEMES.LIGHT
    setTheme(newTheme)
  }

  return {
    // 状态
    theme,
    appReady,

    // 方法
    initApp,
    setTheme,
    toggleTheme
  }
})
